package com.jh.paymentchannel.service;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.yeepay.Conts;
import com.jh.paymentchannel.util.yeepay.Digest;

import cn.jh.common.utils.UUIDGenerator;
import net.sf.json.JSONObject;


@Controller
@EnableAutoConfiguration
public class YBBService {

	private static final Logger log = LoggerFactory.getLogger(YBBService.class);
	private static String key = Conts.hmacKey; // 商户秘钥
	
	/**
	 * 请求参数 验签在数组最后
	 *
	 */
	private static NameValuePair[] param = {
			// 出款金额
			new NameValuePair("amount", ""),
			// 小商户编号
			new NameValuePair("customerNumber", ""),
			// 出款订单号
			new NameValuePair("externalNo", ""),
			// 大商户编号
			new NameValuePair("mainCustomerNumber", ""),
			
			// 出款方式
			new NameValuePair("transferWay", ""),
			
			new NameValuePair("callBackUrl",""),
			
			// 签名串
			new NameValuePair("hmac", ""),
			
	};
	
	@Autowired
	Util util;
	@Autowired
	RegisterAuthService ras;
	
	@Value("${payment.ipAddress}")
	private String ipAddress;
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/paymentchannel/topup/ybbpage")
	public  String returnpay(HttpServletRequest request, HttpServletResponse response, Model model)throws IOException {
			return "zhifuYB";
	}
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/yb/byhand")
	public @ResponseBody String notifycall(HttpServletRequest req, 
			@RequestParam(value = "realAmount") String realAmount,
			@RequestParam(value = "mobile") String mobile) throws IOException{
						Object result = ras.queryByMobile(req, mobile);
						JSONObject json = JSONObject.fromObject(result);
						System.out.println(json);
						JSONObject objj = json.getJSONObject("result");
						System.out.println(objj);
						String customerNumber = objj.getString("customerNumber");
						String mainCustomerNumber = Conts.customerNumber; // 代理商编码
						param[0].setValue(realAmount);
						param[1].setValue(customerNumber);
						param[2].setValue(UUIDGenerator.getUUID().substring(0, 20));
						param[3].setValue(mainCustomerNumber);
						param[4].setValue("1");
						param[5].setValue(ipAddress+"/v1.0/paymentchannel/topup/yb/notify_call");
						param[param.length - 1].setValue(hmacSign());
						PostMethod postMethod = new PostMethod("https://skb.yeepay.com/skb-app/withDrawApi.action");
						HttpClient client = new HttpClient();
						postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
						try {
							postMethod.setRequestBody(param);
							int status2 = client.executeMethod(postMethod);
							log.info("==========结算status2=========="+status2);
							String backinfo = postMethod.getResponseBodyAsString();
							log.info("==========结算backinfo=========="+backinfo);
							if (status2 == HttpStatus.SC_OK) {
								JSONObject obj = JSONObject.fromObject(backinfo);
								if(obj.getString("code").equals("0000")) {
									return "出款成功";
								}else {
									status2 = client.executeMethod(postMethod);
									backinfo = postMethod.getResponseBodyAsString();
									log.info("==========结算backinfo=========="+backinfo);
									obj = JSONObject.fromObject(backinfo);
									if(obj.getString("code").equals("0000")) {
										return "出款成功";
									}else {
										return "出款失败";
									}
								}
							} else {
								return "出款失败";
							}
						} catch (Exception e) {
							e.printStackTrace();
							return "出款失败";
						} finally {
							// 释放连接
							postMethod.releaseConnection();
						}
	}
	/**
	 * 签名
	 *
	 * @return
	 */
	private static String hmacSign() {
		StringBuilder hmacStr = new StringBuilder();
		for (NameValuePair nameValuePair : param) {
			if (nameValuePair.getName().equals("hmac")) {
				continue;
			}
			hmacStr.append(nameValuePair.getValue() == null ? ""
					: nameValuePair.getValue());
			
		}
		
		System.out.println("===============");
		System.out.println("hmacStr.toString()=" + hmacStr.toString());
		System.out.println("===============");
		
		String hmac = Digest.hmacSign(hmacStr.toString(), key);
		
		System.out.println("===============");
		System.out.println("hmac=" + hmac);
		System.out.println("===============");
		
		return hmac;
	}
	
}


